package cn.source.web.controller.tool;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.util.StrUtil;
import cn.source.common.constant.Constants;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.model.LoginUser;
import cn.source.common.exception.base.BaseException;
import cn.source.common.utils.uuid.IdUtils;
import cn.source.framework.web.service.SysLoginService;
import cn.source.system.domain.Vip;
import cn.source.system.domain.dto.OpenIdDto;
import cn.source.system.service.IVipOrderService;
import cn.source.system.service.IVipService;
import io.swagger.annotations.ApiOperation;
import org.dom4j.tree.BaseElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;



import cn.hutool.core.date.DateUtil;
import cn.source.common.core.controller.BaseController;
import cn.source.system.domain.BuzMember;
import cn.source.system.service.IBuzMemberService;

import javax.annotation.Resource;

@RequestMapping("/wx")
@Controller
public class WxController extends BaseController {


    @Autowired
    private IBuzMemberService buzMemberService;


    @Resource
    private IVipService vipService;

	/**
	 * 公众号APPID
	 */
	@Value("${payment.wechat.szywx_js_appid}")
	private String jsAppId;

	/**
	 * 公众号密钥
	 */
	@Value("${payment.wechat.szywx_js_secret}")
	private String jsSecret;

	/**
	 * 判断是否含有特殊字符
	 *
	 * @param str
	 * @return true为包含，false为不包含
	 */
	public static boolean isSpecialChar(String str) {
		String regEx = "[ _`~!#$%^&*()+=|{}&':;',\\[\\]<>/?~！#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.find();
	}


	//效验
	protected static boolean sqlValidate(String str) {
		str = str.toLowerCase();//统一转为小写
		String badStr = "'|select|update|and|or|delete|insert|truncate|char|into"
				+ "|substr|declare|exec|master|drop|execute|sleep|"
				+ "union|;|--|+|,|like|//|/|%|#|*|$|\"|http|cr|lf|<|>|(|)";//过滤掉的sql关键字，可以手动添加
		String[] badStrs = badStr.split("\\|");
		for (int i = 0; i < badStrs.length; i++) {
			if (str.indexOf(badStrs[i]) >= 0) {
				return true;
			}
		}
		return false;
	}

	// wx/wxXcxauth
	@GetMapping("wxXcxauth")
	@ResponseBody
	public JSONObject wxXcxauth(String code,String userId) {
		System.out.println("===========code==========="+code);

		JSONObject json = new JSONObject();

		if(StrUtil.isEmpty(userId)) {
			json.put("status","500");
			json.put("msg","用户ID为空");

		}

		if (isSpecialChar(userId.toString()) || sqlValidate(userId.toString())) {
			json.put("status","500");
			json.put("msg","参数包含非法字符");
		}

		if(StrUtil.isEmpty(code)) {
			json.put("status","500");
			json.put("msg","code为空");

		}

		//根据code获取微信用户openid


		String sns_url = "https://api.weixin.qq.com/sns/jscode2session?appid="+jsAppId+"&secret="+jsSecret+"&js_code="+code+"&grant_type=authorization_code";

		String sns_token="";
		String openid="";

		logger.info("---------- sns_url-----------"+sns_url);
		InputStream is =null;
		try {
			URL urlGet = new URL(sns_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			if(demoJson.containsKey("errcode")) {
				//获取用户openid出错
			}
			System.out.println("JSON字符串2：" + demoJson);
			sns_token = demoJson.getString("access_token");
			openid = demoJson.getString("openid");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
			json.put("status","500");
			json.put("msg",e.toString());
		}finally {
			if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
		}

		logger.info("---------- end openid-----------"+DateUtil.now());





		//logger.info("---------- start save member-----------"+DateUtil.now());

		if(openid!=null) {
			JSONObject data = new JSONObject();
			data.put("openid", openid);

			json.put("data", data);
			json.put("status", 200);
			json.put("msg","成功");

			BuzMember member=buzMemberService.selectBuzMemberById(userId);
			member.setOpenid(openid);
			buzMemberService.updateBuzMember(member);
		}
		return json;
	}



	@GetMapping("auth")
	public String wxAuth(String code,String state) {
		System.out.println(code);
		System.out.println(state);

		// 获取微信相关信息
		//String appID = "wxef2a4572cba58836";//飞标科技
		//String appsecret = "58a439eb2ad6c0694cf43c2369588591";


		//辰任教育
		//		String appID = "wx776976568e5335df";
		//		String appsecret = "4d46e187a069f461a2acd1a6ab73aea5";

		//东南亚
		//String appID = "wxad6e4b10a8bf3eb3";
		//String appsecret = "b27c7944736a48b1fc38595d1a7d5ac3";

		//易指路
		String appID = "wxc448f9e2b830a146";
		String appsecret = "b43299ad4a46f4eb022cbd6c384fc208";
		
		//顺治愿
		//		String appID = "wx1e2c2235d7350137";
		//		String appsecret = "79fa37167c97e7a5b6b479d0b9ef001d";

		String access_token = "";
		String grant_type = "client_credential";//获取access_token填写client_credential
		//这个url链接地址和参数皆不能变
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appID + "&secret=" + appsecret;

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			access_token = demoJson.getString("access_token");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}

		//根据code获取微信用户openid


		String sns_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		String sns_token="";
		String openid="";
		try {
			URL urlGet = new URL(sns_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串2：" + demoJson);
			sns_token = demoJson.getString("access_token");
			openid = demoJson.getString("openid");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}

		String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+sns_token+"&openid="+openid+"&lang=zh_CN";

		String nickname = "";
		String headimgurl = "";
		try {
			URL urlGet = new URL(user_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串3：" + demoJson);
			nickname = demoJson.getString("nickname");
			headimgurl = demoJson.getString("headimgurl");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}

		//System.out.println("nickname:"+nickname);
		//System.out.println("headimgurl:"+headimgurl);
		//System.out.println("openid:"+openid);
		// 判断userid是否存在，不存在则新增，存在，则获取信息 openid作为用户的登录名和密码，昵称则为用户名称
		/*
		SysUser user = new SysUser();
		user.setUserName(openid);
		user.setNickName(nickname);
		user.setAvatar(headimgurl);
		System.out.println(openid);
		if(userService.checkUserNameUnique(user)) {
			// 不存在则新增，存在则获取
			user.setPassword(SecurityUtils.encryptPassword(openid));
			int i = userService.insertUser(user);

		}
		*/
		//SysUser sysuser = userService.selectUserByUserName(openid);
		//System.out.println(sysuser.toString());
		//String token = wxService.getTokenByOpenId(openid);
		return "redirect:"+state;
	}
	// wx/auth2
	@GetMapping("auth2")
	@ResponseBody
	public JSONObject wxAuth(String code) {
		System.out.println("===========code==========="+code);

		// 获取微信相关信息
		//辰任教育
		//String appID = "wx776976568e5335df";
		//String appsecret = "4d46e187a069f461a2acd1a6ab73aea5";

		//东南亚
		//String appID = "wxad6e4b10a8bf3eb3";
		//String appsecret = "b27c7944736a48b1fc38595d1a7d5ac3";

		//易指路
		String appID = "wxc448f9e2b830a146";
		String appsecret = "b43299ad4a46f4eb022cbd6c384fc208";
			
		//顺治愿
		//String appID = "wx1e2c2235d7350137";
		//String appsecret = "79fa37167c97e7a5b6b479d0b9ef001d";

		String access_token = "";
		String grant_type = "client_credential";//获取access_token填写client_credential
		//这个url链接地址和参数皆不能变
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + appID + "&secret=" + appsecret;


		logger.info("---------- start wxcode-----------"+DateUtil.now());

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			// 连接超时30秒
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
			// 读取超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串：" + demoJson);
			access_token = demoJson.getString("access_token");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
			e.printStackTrace();
		}
		logger.info("---------- end wxcode-----------"+DateUtil.now());
		//根据code获取微信用户openid


		String sns_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		//String sns_url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appID+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		String sns_token="";
		String openid="";

		logger.info("---------- start openid-----------"+DateUtil.now());

		try {
			URL urlGet = new URL(sns_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			if(demoJson.containsKey("errcode")) {
				//获取用户openid出错
			}
			System.out.println("JSON字符串2：" + demoJson);
			sns_token = demoJson.getString("access_token");
			openid = demoJson.getString("openid");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
		}

		logger.info("---------- end openid-----------"+DateUtil.now());



		//该方法需要关注公众号
		String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+sns_token+"&openid="+openid+"&lang=zh_CN";

		//String user_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID+"&redirect_uri=fkh5.gxjiankang.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

		String nickname = "";
		String headimgurl = "";

		logger.info("---------- start nickname-----------"+DateUtil.now());

		try {
			URL urlGet = new URL(user_url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSONObject.parseObject(message);
			System.out.println("JSON字符串3：" + demoJson);
			nickname = demoJson.getString("nickname");
			headimgurl = demoJson.getString("headimgurl");
			is.close();
		} catch (Exception e) {
			logger.error("call getAccessToken error",e);
			e.printStackTrace();
		}

		logger.info("---------- end nickname-----------"+DateUtil.now());

		//System.out.println("nickname:"+nickname);
		//System.out.println("headimgurl:"+headimgurl);
		//System.out.println("openid:"+openid);
		// 判断userid是否存在，不存在则新增，存在，则获取信息 openid作为用户的登录名和密码，昵称则为用户名称
		/*
		SysUser user = new SysUser();
		user.setUserName(openid);
		user.setNickName(nickname);
		user.setAvatar(headimgurl);
		System.out.println(openid);
		if(userService.checkUserNameUnique(user)) {
			// 不存在则新增，存在则获取
			user.setPassword(SecurityUtils.encryptPassword(openid));
			int i = userService.insertUser(user);

		}
		*/
		//SysUser sysuser = userService.selectUserByUserName(openid);
		//System.out.println(sysuser.toString());
		//String token = wxService.getTokenByOpenId(openid);
		JSONObject json = new JSONObject();
		//json.put("token", token);

		//logger.info("---------- start save member-----------"+DateUtil.now());
		if(openid!=null) {
			BuzMember member=new BuzMember();
	    	member.setOpenid(openid);
	    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
	    	if(memberList!=null&&memberList.size()>0) {
	    		member=memberList.get(0);

	    		json.put("openid", openid);
	    		json.put("headimgurl", member.getAvatar());
	    		json.put("nickname", member.getMemberName());
	    		json.put("userId",member.getId());
	    	}else {
	    		member.setOpenid(openid);
	    		member.setAvatar(headimgurl);
	    		member.setMemberName(nickname);
	    		member.setId(IdUtils.fastUUID());

				member.setPwd("985211");
				member.setGrade(588);
				member.setSxkm("物理");
				member.setZxkm("化学,生物");
				member.setSfssmz(0);
				member.setSfgjzxdfzx(0);
				member.setSfvip(0);
				member.setYear(2024);
				member.setQggrade(588);
				member.setGxgrade(588);
				member.setSfdfzx(0);
				member.setUserType(1);
	    		//System.out.println("-----member.openId="+member.getOpenid()+";member.Id="+member.getId());
	    		//buzMemberService.insertBuzMember(member);

	    		json.put("openid", openid);
	    		json.put("headimgurl", headimgurl);
	    		json.put("nickname", nickname);
	    		json.put("userId","");
	    	}
		}

    	//logger.info("---------- end save member-----------"+DateUtil.now());
		return json;
	}


	@PostMapping("/api/user/oauth/h5-code-login")
	@ApiOperation("微信公众号openId一键登录")
	@ResponseBody
	public AjaxResult h5CodeOneClickLogin(@RequestBody OpenIdDto openIdRequest) {
		return buzMemberService.h5CodeOneClickLogin(openIdRequest);
	}

	@PostMapping("/test")
	@ApiOperation("")
	@ResponseBody
	public AjaxResult test() {
		Vip one = vipService.findOne(1L);
		System.out.println(one);
		return AjaxResult.success();
	}




}
